//
//  BLDouyuDanmuTableViewController.swift
//  BLLiveTelecast
//
//  Created by BigL055 on 16/6/17.
//  Copyright © 2016年 bigL.liveTelecast.com. All rights reserved.
//

import UIKit
import MJRefresh

class BLDouyuDanmuTableViewController: UITableViewController {
    
    // 弹幕TableView
    var danmuTableView : UITableView?
    // 模型数组
    var danmuModalArray = [BLDanmuModel]()
    
    
    
    let douyuDanmuCellID = "BLDouyuDanmuCellID"
    
    var dataStrS : String = ""
    
    // 房间ID
    var roomID : String = ""
    
    // 是否自动滚动
    var isAutoSrollToBottom = true
    
    // 底部新消息按钮
    var newDanmuButtom : UIButton?
    
}


extension BLDouyuDanmuTableViewController{
    
    func setNewDanmuButtom() {
        
        newDanmuButtom = UIButton(type: UIButtonType.Custom)
        newDanmuButtom?.backgroundColor = UIColor.purpleColor()
        newDanmuButtom?.setTitle("底部有新消息", forState: UIControlState.Normal)
        newDanmuButtom?.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
        newDanmuButtom?.titleLabel?.font = bl_Font_20
        newDanmuButtom?.layer.cornerRadius = BL_Magin
        newDanmuButtom?.sizeToFit()
        newDanmuButtom?.hidden = true
        newDanmuButtom?.addTarget(self, action: #selector(BLDouyuDanmuTableViewController.newDanmuButtomClick), forControlEvents: UIControlEvents.TouchUpInside)
        
        UIApplication.sharedApplication().keyWindow?.addSubview(newDanmuButtom!)
        
        newDanmuButtom?.snp_makeConstraints(closure: { (make) in
            make.bottom.equalToSuperview().offset(-BL_Magin)
            make.centerX.equalToSuperview()
        })
    }
    
    func newDanmuButtomClick() {
        isAutoSrollToBottom = true
        newDanmuButtom?.hidden = true
        
        if danmuModalArray.count > Int(view.frame.height / 20) {
            let indexPath = NSIndexPath(forItem: danmuModalArray.count - 1, inSection: 0)
            tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Bottom)
        }
        
    }
    
    
    /// 拖拽开始 停止弹幕列表就自动滚动
    override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        isAutoSrollToBottom = false
        
        if danmuModalArray.count > Int(view.frame.height / 20) {
            newDanmuButtom?.hidden = false
        }
        
    }
    
    /// 拖拽结束 是弹幕列表底部 就自动滚动
    override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        
        if velocity.y > 0 {
            isAutoSrollToBottom = true
            if danmuModalArray.count > Int(view.frame.height / 20) {
                newDanmuButtom?.hidden = true
            }
        }
    }
    
    
}

extension BLDouyuDanmuTableViewController{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.backgroundColor = UIColor.lightGrayColor()
        
        // 设置新信息按钮
        setNewDanmuButtom()
        //取消间隔线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        tableView.registerClass(BLDouyuDanmuCell.self, forCellReuseIdentifier: douyuDanmuCellID)
        //监听通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(receiveNotification(_:)), name: kReceiveMessageNotification, object: nil)
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        contentServerSocket()
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        newDanmuButtom?.hidden = true
        //断开弹幕连接
        BLDanmuServerTool.shareInstance.cutServer()
        print("BLDouyuDanmuTableViewController disappear")
    }
    
    
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return danmuModalArray.count
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(douyuDanmuCellID, forIndexPath: indexPath) as! BLDouyuDanmuCell
        if danmuModalArray.count != 0 {
            cell.modal = danmuModalArray[indexPath.item]
        }
        return cell
        
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 20
    }
}



// MARK: - 弹幕获取与tableView刷新
extension BLDouyuDanmuTableViewController{
    
    /// 读取数据
    func receiveNotification(notification : NSNotification) {
        
        let dataStr = ((notification.object)! as! String)
        
        let model : BLDanmuModel = BLDanmuModel()
        
        
        let typeStr = bl_regexWithPattern(DanmuParameterRegex.DanmuType.rawValue, inputStr: dataStr)[0]
        
        if typeStr == BLCellType.CellChatMessage.rawValue {
            model.type = BLCellType.CellChatMessage
            model.setModelFromStirng(dataStr)
            danmuModalArray.append(model)
        }
        else if typeStr == BLCellType.CellGiftGivingNotice.rawValue {
            model.type = BLCellType.CellGiftGivingNotice
            model.setModelFromStirng(dataStr)
            danmuModalArray.append(model)
        }
        else if typeStr == BLCellType.CellUserEnter.rawValue {
            model.type = BLCellType.CellUserEnter
            model.setModelFromStirng(dataStr)
            danmuModalArray.append(model)
        }
        else if typeStr == BLCellType.CellBanUser.rawValue {
            model.type = BLCellType.CellBanUser
            model.setModelFromStirng(dataStr)
            danmuModalArray.append(model)
        }
        else if typeStr == BLCellType.CellUpGrade.rawValue {
            model.type = BLCellType.CellUpGrade
            model.setModelFromStirng(dataStr)
            danmuModalArray.append(model)
        }
        else if typeStr == BLCellType.CellKeeplive.rawValue {
            /// 保持连接
        }
        else{
            print(dataStr)
            //将弹幕写入到桌面
            dataStrS = dataStrS + "\n" + dataStr
            bl_writerToDesktop(dataStrS, filename: "DanMuDataStr.txt")
        }
        
        
        tableView.reloadData()
        
        if isAutoSrollToBottom {
            
            if danmuModalArray.count > Int(view.frame.height / 20) {
                let indexPath = NSIndexPath(forItem: danmuModalArray.count - 1, inSection: 0)
                
                tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.Bottom)
            }
            
        }
        
    }
    
    
    // 连接服务器
    private func contentServerSocket() {
                
        BLDanmuServerTool.shareInstance.startServer(roomID)
        
    }
    
}
